<?php

namespace app\uniapp\service;
use app\model\store\GoodsCate;
use app\uniapp\service\traits\InstanceTrait;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;

class GoodsCateService extends UniBaseService
{

    use InstanceTrait;

    function initialize()
    {
        $this->model = new GoodsCate();
    }

    public function query(): Query
    {
        return $this->makeQuery()->where('show_type', 1);
    }

    function formatData(array $data): array
    {
        return $data;
    }


    /** 根据分类id获取下级分类
     * @param $arr
     * @param $id
     * @param $lev
     * @return array 一维数组
     * @return array 一维数组
     */
    public function tree($data,$id=0,$lev=1): array
    {
        $subs = array();
        foreach($data as $v)
        {
            if($v['pid'] == $id){
                $v['lev'] = $lev;
                $v['l_title'] = str_repeat("——", $lev-1).$v['title'];
                $subs[] = $v;
                $subs = array_merge($subs,$this->tree($data, $v['id'], $lev+1));
            }
        }
        return $subs;
    }

    /**
     * 二维数组
     * @param $data
     * @param $id
     * @param $lev
     * @return array
     */
    public function childrenTree($data, $id=0, $lev=1): array
    {
        $subs = array();
        foreach($data as $v)
        {
            if($v['pid'] == $id){
                $v['lev'] = $lev;
                $v['children'] = $this->childrenTree($data, $v['id'], $lev+1);
                $subs[] = $v;
            }
        }
        return $subs;
    }



    /**
     * 获取所有下级分类id
     * @param $data
     * @param $id
     * @return array
     */
    public function childrenIds($data, $id): array
    {
        $tree = $this->tree($data, $id);
        $ids = [];
        foreach ($tree as $v){
            $ids[] = $v['id'];
        }
        return $ids;
    }


    /**
     * 获取所有分类
     * @return array|Collection|Query[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAllCates(): array|Collection
    {
        return $this->query()->select();
    }






}
